import axios from 'axios'
import { getCookie } from '@/utils/cookie'
import {
  BASE_URL,
  CODE_FAILURE,
  CODE_SUCCESS,
  RESPONSE_TYPE,
  TIME_OUT
} from './axios.config'

const request = axios.create({
  timeout: TIME_OUT,
  baseURL: BASE_URL,
  responseType: RESPONSE_TYPE
})

request.interceptors.request.use(
  (config) => {
    const token = getCookie('bonyear-access_token')
    const tenantID = getCookie('bonyear-tenantId')

    if (token) {
      config.headers.Accept = 'application/json'
      config.headers.Authorization = `Bearer ${token}`
      config.headers['TENANT-ID'] = tenantID
    } else {
      config.headers.isToken = false
      config.headers.Authorization = 'Basic Ynl0OmJ5dA=='
    }

    if (config.headers['Content-Type'] === 'multipart/form-data') {
      return config
    }
    return config
  },
  (error) => Promise.reject(error)
)

request.interceptors.response.use(
  (response) => {
    const { code, data, msg } = response.data

    if (code === CODE_SUCCESS) {
      return data
    }
    if (code === CODE_FAILURE) {
      window['$message'].closeAll()
      window['$message'].error(msg)
      return data
    }
    return response
  },
  (error) => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
        case 428:
          window['$message'].closeAll()
          window['$message'].error('请先登录')
          window.location.href = '/login'
          return Promise.reject()
        default:
          window['$message'].closeAll()
          window['$message'].error('服务器内部错误')
          return Promise.reject()
      }
    } else {
      return Promise.reject()
    }
  }
)

export default request
